package com.qf.utils;

import com.qf.pojo.Usermanager;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.ResourceBundle;

/**
 * 2019/11/25 0025
 * Author->DT
 * qmxc
 * 行到水穷处 坐看云起时
 * 模块：登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    //拦截器开始执行(拦截器拦截的是请求，不拦截页面)
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、判断是否为匿名地址:(用户在未登录状态下可以访问的资源)
        //1.1 读取属性文件中的信息
        ResourceBundle anon = ResourceBundle.getBundle("anony");
        //1.2获取请求地址
        String requestURI = request.getRequestURI();
        if (anon.containsKey(requestURI)){
            //当前请求地址是匿名地址,放行
            return true;
        }
        //2、判断Session是否有值
        HttpSession session = request.getSession();
        Usermanager user = (Usermanager) session.getAttribute("user");
        if (user!=null){
            return true;
        }else {
            //3、根据结果跳转页面
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.print("<script>alert('请登录！');location.href='/login.jsp'</script>");
            return false;
        }


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
